﻿using System;
using System.IO;

using Infrastructure.Diagnostics;
using Infrastructure.ServicesManager;
using TempEmployees.BLL;

namespace TempEmployees.Web
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            ServiceEngineSingleton.Init();

            //
            // Directories

            if (!Directory.Exists(TempEmployees.BLL.Forms.ProduceForms.ROOT_DIR)) Directory.CreateDirectory(TempEmployees.BLL.Forms.ProduceForms.ROOT_DIR);
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Logger.Info("Session start, ID({0})", Session.SessionID);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().InnerException;
            Server.ClearError();
            if (ex is NoSessionStateException)
            {
                Session.Clear();
                Response.Redirect(GUIServices.PAGE_LOGIN);
            }
            else
            {
                if (ex == null)  return;
                Logger.Error(Logger.ExceptionMessage(ex));
                APageData.Set(new ErrorPageData(ex));
                Response.Redirect(GUIServices.PAGE_ERROR);
            }      
        }

        protected void Session_End(object sender, EventArgs e)
        {
            Logger.Info("Session end, ID({0})", Session.SessionID);
        }

        protected void Application_End(object sender, EventArgs e)
        {
            Logger.Info("Application end");
        }
    }
}